﻿using System;
using System.Windows.Forms;

namespace HyperplaneTech.CdrPlugin {

    /// <summary>
    /// 窗体工具类
    /// </summary>
    public class FormUtil {

        /// <summary>
        /// 显示对话框窗体
        /// </summary>
        /// <param name="frm">窗体</param>
        public static void ShowDialog(Form frm) {
            if (frm == null) {
                return;
            }
            frm.ShowInTaskbar = false;
            frm.ShowDialog();
            frm.Activate();
        }

        /// <summary>
        /// 在指定句柄的容器中显示窗体
        /// </summary>
        /// <param name="frm">窗体</param>
        /// <param name="hwnd">句柄</param>
        public static void ShowForm(Form frm, IntPtr hwnd) {
            if (frm == null) {
                return;
            }
            if (hwnd == null) {
                return;
            }
            // 如果窗体已经打开了，则还原窗体的位置
            if (frm.Visible) {
                frm.WindowState = FormWindowState.Normal;
            } else if (!frm.IsDisposed) {
                frm.ShowInTaskbar = false;
                frm.Show(new WindowWrapper(hwnd));
                frm.Activate();
            }
        }

    }

    /// <summary>
    /// 窗体包装器
    /// </summary>
    public class WindowWrapper : IWin32Window {

        // 窗体句柄
        private readonly IntPtr _hwnd;

        /// <summary>
        /// 构造器
        /// </summary>
        /// <param name="handle">句柄</param>
        public WindowWrapper(IntPtr handle) {
            _hwnd = handle;
        }

        /// <summary>
        /// 获取窗体句柄
        /// </summary>
        public IntPtr Handle {
            get {
                return _hwnd;
            }
        }
    }

}